<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聚合定义</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .step-container {
            display: none;
        }
        .step-container.active {
            display: block;
        }
        .field-group {
            border: 1px solid #ddd;
            padding: 15px;
            margin-bottom: 15px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
<div class="container mt-4">
    <div class="progress mb-4">
        <div class="progress-bar" role="progressbar" style="width: 25%"></div>
    </div>

    <!-- Step 1: Aggregate Definition -->
    <div class="step-container active" id="step1">
        <h3>步骤 1: 定义聚合</h3>
        <div class="mb-3">
            <label class="form-label">名称</label>
            <input type="text" class="form-control" id="name">
        </div>
        <div class="mb-3">
            <label class="form-label">英文名称</label>
            <input type="text" class="form-control" id="enName">
        </div>
        <div class="mb-3">
            <label class="form-label">版本</label>
            <input type="text" class="form-control" id="version">
        </div>
        <div class="mb-3">
            <label class="form-label">模块名</label>
            <input type="text" class="form-control" id="moduleName">
        </div>
        <div class="mb-3">
            <label class="form-label">项目名</label>
            <input type="text" class="form-control" id="projectName">
        </div>
        <div class="mb-3">
            <label class="form-label">公司前缀</label>
            <input type="text" class="form-control" id="comPrefix">
        </div>
        <div class="mb-3">
            <label class="form-label">创建者</label>
            <input type="text" class="form-control" id="creator">
        </div>
        <div class="mb-3">
            <div class="form-check">
                <input class="form-check-input" type="checkbox" id="multiTenant">
                <label class="form-check-label">多租户</label>
            </div>
        </div>

        <!-- 聚合字段部分修改 -->
        <h4>聚合字段</h4>
        <div id="aggregateFields">
            <div class="mb-3">
                <label class="form-label">批量添加字段（每行一个字段，格式：字段名称(字段英文名称) 例如：电脑编号(evaluationComputerCode)）</label>
                <textarea class="form-control" id="aggregateFieldsText" rows="5" placeholder="电脑编号(evaluationComputerCode)&#10;电脑名称(evaluationComputerName)"></textarea>
            </div>
            <button type="button" class="btn btn-primary mb-3" onclick="parseAndAddFields('aggregateFieldsText', 'aggregateFieldsList', 'aggregateField')">解析并添加字段</button>
            <div id="aggregateFieldsList"></div>
        </div>

        <button type="button" class="btn btn-primary" onclick="nextStep()">下一步</button>
    </div>

    <!-- Step 2: Entity Definition -->
    <div class="step-container" id="step2">
        <h3>步骤 2: 定义实体</h3>
        <div id="entities">
            <button type="button" class="btn btn-secondary mb-3" onclick="addEntity()">添加实体</button>
            <div id="entitiesList"></div>
        </div>
        <button type="button" class="btn btn-secondary" onclick="previousStep()">上一步</button>
        <button type="button" class="btn btn-primary" onclick="nextStep()">下一步</button>
    </div>

    <!-- Step 3: Value Object Definition -->
    <div class="step-container" id="step3">
        <h3>步骤 3: 定义值对象</h3>
        <div id="valueObjects">
            <button type="button" class="btn btn-secondary mb-3" onclick="addValueObject()">添加值对象</button>
            <div id="valueObjectsList"></div>
        </div>
        <button type="button" class="btn btn-secondary" onclick="previousStep()">上一步</button>
        <button type="button" class="btn btn-primary" onclick="generateJson()">生成JSON</button>
    </div>
</div>

<script>
    let currentStep = 1;
    let entityCounter = 0;
    let voCounter = 0;

    function updateProgress() {
        const progress = (currentStep - 1) * 33.33;
        document.querySelector('.progress-bar').style.width = progress + '%';
    }

    function showStep(step) {
        document.querySelectorAll('.step-container').forEach(container => {
            container.classList.remove('active');
        });
        document.getElementById('step' + step).classList.add('active');
        currentStep = step;
        updateProgress();
    }

    function nextStep() {
        showStep(currentStep + 1);
    }

    function previousStep() {
        showStep(currentStep - 1);
    }

    function addField(containerId, prefix) {
        const container = document.getElementById(containerId);
        const fieldGroup = document.createElement('div');
        fieldGroup.className = 'field-group';

        // 根据前缀决定默认类型
        let defaultType = "";
        if (prefix === 'voField') {
            defaultType = "String";
        }

        let innerHTML = `
            <div class="mb-3">
                <label class="form-label">字段名称</label>
                <input type="text" class="form-control" name="${prefix}Name">
            </div>
            <div class="mb-3">
                <label class="form-label">字段英文名称</label>
                <input type="text" class="form-control" name="${prefix}EnName">
            </div>
            <div class="mb-3">
                <label class="form-label">字段类型</label>
                <input type="text" class="form-control" name="${prefix}Type" value="${defaultType}">
            </div>
            `;
        if (prefix === 'voField') {
            innerHTML += `
            <div class="mb-3">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="${prefix}Required">
                    <label class="form-check-label">必填</label>
                </div>
            </div>
            <div class="mb-3">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="${prefix}ToEquals">
                    <label class="form-check-label">用于相等性比较</label>
                </div>
            </div>
            `;
        }

        innerHTML += `<button type="button" class="btn btn-danger" onclick="this.parentElement.remove()">删除字段</button>`;
        fieldGroup.innerHTML = innerHTML;
        container.appendChild(fieldGroup);
    }

    function addAggregateField() {
        addField('aggregateFieldsList', 'aggregateField');
    }

    // function addEntity() {
    //     entityCounter++;
    //     const container = document.getElementById('entitiesList');
    //     const entityGroup = document.createElement('div');
    //     entityGroup.className = 'field-group';
    //     const entityFieldsListId = `entityFieldsList_${entityCounter}`;
    //     entityGroup.innerHTML = `
    //             <h4>实体</h4>
    //             <div class="mb-3">
    //                 <label class="form-label">实体名称</label>
    //                 <input type="text" class="form-control" name="entityName">
    //             </div>
    //             <div class="mb-3">
    //                 <label class="form-label">实体英文名称</label>
    //                 <input type="text" class="form-control" name="entityEnName">
    //             </div>
    //             <div class="entity-fields">
    //                 <button type="button" class="btn btn-secondary mb-3" onclick="addEntityField('${entityFieldsListId}')">添加字段</button>
    //                 <div class="entity-fields-list" id="${entityFieldsListId}"></div>
    //             </div>
    //             <button type="button" class="btn btn-danger" onclick="this.parentElement.remove()">删除实体</button>
    //         `;
    //     container.appendChild(entityGroup);
    // }

    // function addEntityField(containerId) {
    //     addField(containerId, 'entityField');
    // }

    // function addValueObject() {
    //     voCounter++;
    //     const container = document.getElementById('valueObjectsList');
    //     const voGroup = document.createElement('div');
    //     voGroup.className = 'field-group';
    //     const voFieldsListId = `voFieldsList_${voCounter}`;
    //     voGroup.innerHTML = `
    //             <h4>值对象</h4>
    //             <div class="mb-3">
    //                 <label class="form-label">值对象名称</label>
    //                 <input type="text" class="form-control" name="voName">
    //             </div>
    //             <div class="mb-3">
    //                 <label class="form-label">值对象英文名称</label>
    //                 <input type="text" class="form-control" name="voEnName">
    //             </div>
    //
    //             <div class="mb-3">
    //                 <div class="form-check">
    //                     <input class="form-check-input" type="checkbox" name="voIsEnum">
    //                     <label class="form-check-label">是否枚举</label>
    //                 </div>
    //             </div>
    //             <div class="vo-fields">
    //                 <button type="button" class="btn btn-secondary mb-3" onclick="addVOField('${voFieldsListId}')">添加字段</button>
    //                 <div class="vo-fields-list" id="${voFieldsListId}"></div>
    //             </div>
    //             <button type="button" class="btn btn-danger" onclick="this.parentElement.remove()">删除值对象</button>
    //         `;
    //     container.appendChild(voGroup);
    // }
    //
    // function addVOField(containerId) {
    //     addField(containerId, 'voField');
    // }

    function collectFields(container, prefix) {
        const fields = [];
        container.querySelectorAll(`.field-group`).forEach(group => {
            const field = {
                name: group.querySelector(`[name="${prefix}Name"]`).value,
                enName: group.querySelector(`[name="${prefix}EnName"]`).value,
                type: group.querySelector(`[name="${prefix}Type"]`).value,
                required: group.querySelector(`[name="${prefix}Required"]`)?.checked,
                toEquals: group.querySelector(`[name="${prefix}ToEquals"]`)?.checked,
            };
            fields.push(field);
        });
        return fields;
    }

    function generateJson() {
        const aggregateData = {
            name: document.getElementById('name').value,
            enName: document.getElementById('enName').value,
            version: document.getElementById('version').value,
            moduleName: document.getElementById('moduleName').value,
            comPrefix: document.getElementById('comPrefix').value,
            projectName: document.getElementById('projectName').value,
            creator: document.getElementById('creator').value,
            multiTenant: document.getElementById('multiTenant').checked,
            fields: collectFields(document.getElementById('aggregateFieldsList'), 'aggregateField'),
            entities: [],
            valueObjects: []
        };

        // Collect entities
        document.querySelectorAll('#entitiesList > .field-group').forEach(entityGroup => {
            const entity = {
                name: entityGroup.querySelector('[name="entityName"]').value,
                enName: entityGroup.querySelector('[name="entityEnName"]').value,
                fields: collectFields(entityGroup.querySelector('.entity-fields-list'), 'entityField')
            };
            aggregateData.entities.push(entity);
        });

        // Collect value objects
        document.querySelectorAll('#valueObjectsList > .field-group').forEach(voGroup => {
            const valueObject = {
                name: voGroup.querySelector('[name="voName"]').value,
                enName: voGroup.querySelector('[name="voEnName"]').value,
                isEnum: voGroup.querySelector('[name="voIsEnum"]').checked,
                fields: collectFields(voGroup.querySelector('.vo-fields-list'), 'voField')
            };
            aggregateData.valueObjects.push(valueObject);
        });
        // Create and download JSON file
        const jsonStr = JSON.stringify(aggregateData, null, 2);

        //调用后端接口/generate/addAggregateRoot
        fetch('/meditate/generate/download', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: jsonStr
        }).then(response => {
            if (response.ok) {
                return response.blob();
            } else {
                throw new Error('Failed to generate JSON');
            }
        }).then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = '结果.zip';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            // alert('ZIP文件已生成并下载');
        }).catch(error => {
            console.error('Error:', error);
        });

    }

    <!-- 修改实体添加逻辑 -->
    function addEntity() {
        entityCounter++;
        const container = document.getElementById('entitiesList');
        const entityGroup = document.createElement('div');
        entityGroup.className = 'field-group';
        const entityFieldsListId = `entityFieldsList_${entityCounter}`;
        const entityFieldsTextId = `entityFieldsText_${entityCounter}`;
        entityGroup.innerHTML = `
            <h4>实体</h4>
            <div class="mb-3">
                <label class="form-label">实体名称</label>
                <input type="text" class="form-control" name="entityName">
            </div>
            <div class="mb-3">
                <label class="form-label">实体英文名称</label>
                <input type="text" class="form-control" name="entityEnName">
            </div>
            <div class="entity-fields">
                <div class="mb-3">
                    <label class="form-label">批量添加字段（每行一个字段，格式：字段名称(字段英文名称)）注：值对象务必指定必填和相等匹配</label>
                    <textarea class="form-control" id="${entityFieldsTextId}" rows="5" placeholder="电脑编号(evaluationComputerCode)&#10;电脑名称(evaluationComputerName)"></textarea>
                </div>
                <button type="button" class="btn btn-primary mb-3" onclick="parseAndAddFields('${entityFieldsTextId}', '${entityFieldsListId}', 'entityField')">解析并添加字段</button>
                <div class="entity-fields-list" id="${entityFieldsListId}"></div>
            </div>
            <button type="button" class="btn btn-danger" onclick="this.parentElement.remove()">删除实体</button>
        `;
        container.appendChild(entityGroup);
    }

    <!-- 修改值对象添加逻辑 -->
    function addValueObject() {
        voCounter++;
        const container = document.getElementById('valueObjectsList');
        const voGroup = document.createElement('div');
        voGroup.className = 'field-group';
        const voFieldsListId = `voFieldsList_${voCounter}`;
        const voFieldsTextId = `voFieldsText_${voCounter}`;
        voGroup.innerHTML = `
            <h4>值对象</h4>
            <div class="mb-3">
                <label class="form-label">值对象名称</label>
                <input type="text" class="form-control" name="voName">
            </div>
            <div class="mb-3">
                <label class="form-label">值对象英文名称</label>
                <input type="text" class="form-control" name="voEnName">
            </div>
            <div class="mb-3">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="voIsEnum">
                    <label class="form-check-label">是否枚举</label>
                </div>
            </div>
            <div class="vo-fields">
                <div class="mb-3">
                    <label class="form-label">批量添加字段（每行一个字段，格式：字段名称(字段英文名称)）</label>
                    <textarea class="form-control" id="${voFieldsTextId}" rows="5" placeholder="电脑编号(evaluationComputerCode)&#10;电脑名称(evaluationComputerName)"></textarea>
                </div>
                <button type="button" class="btn btn-primary mb-3" onclick="parseAndAddFields('${voFieldsTextId}', '${voFieldsListId}', 'voField')">解析并添加字段</button>
                <div class="vo-fields-list" id="${voFieldsListId}"></div>
            </div>
            <button type="button" class="btn btn-danger" onclick="this.parentElement.remove()">删除值对象</button>
        `;
        container.appendChild(voGroup);
    }
    function parseAndAddFields(textareaId, containerId, prefix) {
        const textarea = document.getElementById(textareaId);
        const container = document.getElementById(containerId);
        const content = textarea.value.trim();

        // 确保文本内容非空
        if (!content) {
            console.log('文本框内容为空');
            return;
        }

        // 分割行并打印行数
        const lines = content.split('\n');
        console.log(`共有${lines.length}行需要处理`);

        // 遍历每一行
        for (let i = 0; i < lines.length; i++) {
            let line = lines[i].trim();
            if (!line) {
                console.log(`第${i+1}行为空，跳过`);
                continue; // 跳过空行
            }

            console.log(`处理第${i+1}行: ${line}`);

            // 解析字段名称和英文名称
            // 匹配格式如：电脑编号(evaluationComputerCode) 或 电脑名称（evaluationComputerName）
            // 同时支持中文括号和英文括号
            const regex = /(.+)\s*[\(（]([^)）]+)[\)）]/;
            const match = line.match(regex);

            if (match) {
                const name = match[1].trim();
                let enName = match[2].trim();
                if (enName.length > 0) {
                    enName = enName.charAt(0).toLowerCase() + enName.slice(1);
                }
                console.log(`解析结果: 名称=${name}, 英文名称=${enName}`);

                // 根据前缀决定默认类型
                let defaultType = "";
                if (prefix === 'voField') {
                    defaultType = "String";
                }

                // 创建字段
                const fieldGroup = document.createElement('div');
                fieldGroup.className = 'field-group';
                let innerHTML = `
                <div class="mb-3">
                    <label class="form-label">字段名称</label>
                    <input type="text" class="form-control" name="${prefix}Name" value="${name}">
                </div>
                <div class="mb-3">
                    <label class="form-label">字段英文名称</label>
                    <input type="text" class="form-control" name="${prefix}EnName" value="${enName}">
                </div>
                <div class="mb-3">
                    <label class="form-label">字段类型</label>
                    <input type="text" class="form-control" name="${prefix}Type" value="${defaultType}">
                </div>
            `;

                if (prefix === 'voField') {
                    innerHTML += `
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="${prefix}Required">
                            <label class="form-check-label">必填</label>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="${prefix}ToEquals">
                            <label class="form-check-label">用于相等性比较</label>
                        </div>
                    </div>
                `;
                }

                innerHTML += `<button type="button" class="btn btn-danger" onclick="this.parentElement.remove()">删除字段</button>`;
                fieldGroup.innerHTML = innerHTML;
                container.appendChild(fieldGroup);
                console.log(`已添加字段: ${name}`);
            } else {
                console.log(`第${i+1}行格式不匹配: ${line}`);
            }
        }

        // 清空文本框
        textarea.value = '';
        console.log('文本框已清空');
    }
</script>
</body>
</html>